package com.example.star.view.center;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.star.R;
import com.example.star.adapter.BuyNowAdapter;
import com.example.star.api_service.ApiBuyNow;
import com.example.star.entity.BuyNow;
import com.example.star.retrofit.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PendingEvaluationActivity extends AppCompatActivity {

    private ListView listView;
    private BuyNowAdapter adapter;
    private TextView tvEmptyHint;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pending_evaluation);

        // 从 SharedPreferences 中获取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String userName = sharedPreferences.getString("username", "");

        listView = findViewById(R.id.listView);
        tvEmptyHint = findViewById(R.id.tv_empty_hint);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);

        // 触发首次数据获取
        fetchPendingPaymentOrders(userName);

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 检查列表是否在最顶部
            if (isListViewAtTop()) {
                // 触发刷新时重新获取数据
                fetchPendingPaymentOrders(userName);
            } else {
                // 如果不在最顶部，取消刷新
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(this, "请先滑动到顶部", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置下拉刷新的颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);


        // 监听 ListView 的滚动事件
        listView.setOnScrollListener(new android.widget.AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 检查是否可以下拉刷新
                swipeRefreshLayout.setEnabled(isListViewAtTop());
            }
        });
    }

    private boolean isListViewAtTop() {
        return listView.getFirstVisiblePosition() == 0 &&
                (listView.getChildAt(0) == null || listView.getChildAt(0).getTop() >= 0);
    }

    private void fetchPendingPaymentOrders(String userName) {
        // 清空原适配器的数据
        if (adapter != null) {
            adapter.clear();
        }

        ApiBuyNow apiBuyNow = ApiClient.getApiBuyNow();
        Call<List<BuyNow>> call = apiBuyNow.getBuyNowsByuserNameAndOrderStatus(userName, "待评价");

        call.enqueue(new Callback<List<BuyNow>>() {
            @Override
            public void onResponse(Call<List<BuyNow>> call, Response<List<BuyNow>> response) {
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
                if (response.isSuccessful()) {
                    List<BuyNow> buyNows = response.body();
                    if (buyNows != null && !buyNows.isEmpty()) {
                        // 有数据时隐藏提示信息
                        tvEmptyHint.setVisibility(android.view.View.GONE);
                        adapter = new BuyNowAdapter(PendingEvaluationActivity.this, buyNows);
                        listView.setAdapter(adapter);
                    } else {
                        // 无数据时显示提示信息
                        tvEmptyHint.setText("暂无待评价记录");
                        tvEmptyHint.setVisibility(android.view.View.VISIBLE);
                        Toast.makeText(PendingEvaluationActivity.this, "暂无待评价记录", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(PendingEvaluationActivity.this, "获取待评价数据失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(PendingEvaluationActivity.this, "获取待评价数据失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<List<BuyNow>> call, Throwable t) {
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(PendingEvaluationActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}